﻿import com.audiopackage.GBuffer;
import com.audiopackage.GDelimiter;
import com.audiopackage.GTargetClipSupplier;

/*
* class GSound extends Sound
* extends SoundClass to have better control
* over the playing sounds. More than 8 playing
* Sounds are not allowed, so you cannot break
* a running soundloop accidentally.
* The Success of method:
* 	GSoundInstance.start();
* ...can be accessed in the return value (Boolean)
*/

class com.audiopackage.GSound extends Sound
{
	private var buffer: GBuffer;
	private var delimiter: GDelimiter;
	
	private var targetClip: MovieClip;
	private var linkageId: String;
	
	private var busy: Boolean;
	
	private var o_onSoundComplete: Function;
	
	var addListener: Function;
	var removeListener: Function;
	private var broadcastMessage: Function;

	function GSound( targetClip: MovieClip )
	{
		super( this.targetClip = ( targetClip == undefined ) ? GTargetClipSupplier.getTargetClip() : targetClip );
		
		busy = false;
		delimiter = GDelimiter.getInstance();
		
		AsBroadcaster.initialize( this );
	}
	
	function attachSound( linkageId: String ): GSound
	{
		super.attachSound( this.linkageId = linkageId );
		return this;
	}
	
	function start(): Boolean
	{
		if( !delimiter.isLimit() || getLinkageId() == undefined )
		{
			super.start.apply( this, arguments );
			delimiter.push();
			broadcastMessage.apply( this , ['onStart' , this ].concat( arguments ) );
			busy = true;
			buffer = new GBuffer( this );
			return true;
		}
		else
		{
			return false;
		}
	}
	
	function stop( Void ): Void
	{
		if ( busy )
		{
			busy = false;
			delimiter.pop();
			super.stop();
		}
	}
	
	function isBusy(): Boolean
	{
		return busy;
	}
	
	function getTargetClip(): MovieClip
	{
		return targetClip;
	}
	
	function getLinkageId(): String
	{
		return linkageId;
	}
	
	function set onSoundComplete( f: Function ): Void
	{
		o_onSoundComplete = f;
	}
	
	function get onSoundComplete(): Function
	{
		if( arguments.caller == null )	//-- Call from Soundcard
		{
			busy = false;
			delimiter.pop();
			GBuffer.clear( buffer );
		}
		return o_onSoundComplete;
	}
}